package com.hmall.item.web;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
@Slf4j
@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/list")
    public PageDTO<Item> list(@RequestParam("page") Integer page,@RequestParam("size")Integer size){
        return itemService.page(page,size);
    }

    @GetMapping("/{id}")
    public Item getById(@PathVariable("id") Long id){
        return itemService.getById(id);
    }

    @PostMapping
    public void save(@RequestBody Item item){
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
        rabbitTemplate.convertAndSend(MqConstants.HM_EXCHANGE,MqConstants.HM_INSERT_KEY,item.getId());
    }



    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable("id") Long id,
                       @PathVariable("status")Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        if(status==2){
            rabbitTemplate.convertAndSend(MqConstants.HM_EXCHANGE,MqConstants.HM_DELETE_KEY,id);
        }
        rabbitTemplate.convertAndSend(MqConstants.HM_EXCHANGE,MqConstants.HM_INSERT_KEY,id);
        log.info("商品已修改"+id+"状态为"+status);
    }


     @PutMapping
    public void update(@RequestBody Item item){
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MqConstants.HM_EXCHANGE,MqConstants.HM_INSERT_KEY,item.getId());
    }



     @DeleteMapping("/{id}")
     public void delete(@PathVariable("id")long id){
        itemService.removeById(id);
        rabbitTemplate.convertAndSend(MqConstants.HM_EXCHANGE,MqConstants.HM_DELETE_KEY,id);
    }


    @PutMapping("/stock/{itemId}/{num}")
    public boolean update(@PathVariable("itemId") Long itemId,@PathVariable("num") int num){
         return  itemService.update(itemId,num);
    }



    @PutMapping("/stock/recover/{itemId}/{num}")
    public void recoverStock(@PathVariable("itemId") Long itemId, @PathVariable("num") Integer num) {
        itemService.recoverStock(itemId, num);
    }
}
